package com.iotechn.microunimall.apigw;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/11/14
 * Time: 15:34
 */
public class Test {

    private static void initFlowRules(){
        ParamFlowRule rule = new ParamFlowRule("HelloWorld")
                .setParamIdx(0)
                .setGrade(RuleConstant.FLOW_GRADE_QPS)
                .setCount(1);
        ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    }

    public static void main(String[] args) throws Exception {
        // 配置规则.
        initFlowRules();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        // 1.5.0 版本开始可以直接利用 try-with-resources 特性，自动 exit entry
                        try (Entry entry = SphU.entry("HelloWorld", EntryType.IN, 1, "obj")) {
                            // 被保护的逻辑
                            System.out.println("hello world" + Thread.currentThread().getName());
                            Thread.sleep(20);
                        } catch (BlockException ex) {
                            // 处理被流控的逻辑
                            //System.out.println("blocked!");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }


        Thread.sleep(Long.MAX_VALUE);
    }

}
